import { render, type Directive, type DirectiveBinding } from "vue";
import showInfo from './index.vue'
import { router } from '@/router/index'


export const pageShow: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding;
    if (value) {
      if (!value.show) {
        const parentNode = el.parentNode
        // parentNode?.removeChild(el);
        el.style.display = 'none'
        const div = document.createElement('div');
        div.className = 'directive-page-show'
        div.style.width = '100%'
        div.style.height = '100%'
        let ele = h(showInfo, { text: value.text })
        render(ele, div);
        parentNode?.appendChild(div);
        const stopWatch = watch(() =>
          router.currentRoute.value.path,
          () => {
            div.remove()
            stopWatch()
          }, {
          deep: true
        })
      }
    } else {
      throw new Error(
        "v-page-show directive need a value to determine whether to show"
      );
    }
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding;
    if (value) {
      const parentNode = el.parentNode
      if (value.show) {
        el.style.display = ''
        if (parentNode?.querySelector('.directive-page-show')) {
          parentNode.removeChild(parentNode.querySelector('.directive-page-show')!)
        }
      } else {
        if (!parentNode?.querySelector('.directive-page-show')) {
          el.style.display = 'none'
          const div = document.createElement('div');
          div.className = 'directive-page-show'
          div.style.width = '100%'
          div.style.height = '100%'
          let ele = h(showInfo, { text: value.text })
          render(ele, div);
          parentNode?.appendChild(div);
          const stopWatch = watch(() =>
            router.currentRoute.value.path,
            () => {
              div.remove()
              stopWatch()
            }, {
            deep: true
          })
        }
      }
    } else {
      throw new Error(
        "v-page-show directive need a value to determine whether to show"
      );
    }
  }
};
